package com.Stash.Controller;


import com.Stash.Domain.*;
import com.Stash.Service.AdminService;
import com.Stash.Service.GeneralService;
import com.Stash.Utils.Code;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;


@RestController // 将web变成bean，并将最后的return的数据作为整体返回给前端
//@RequestMapping("/books") // 用于修饰类，则是该类所有方法的总路径，修饰方法则是方法的路径

@RequestMapping("/General")
public class GeneralController {

    @Autowired //自动装配
    private GeneralService General;

    @Autowired //自动装配
    private AdminService Admin;

    // 登录
    @PostMapping("/AdminLogin")
    public Result AdminLogin(@RequestBody admins admins) {
        admins admins1 = General.AdminLogin(admins);
        if (admins1 == null) {
            return new Result(Code.ERROR.getValue(), "账号或密码不对");
        }
        if (admins1.getAdminLeave().equals(2)) {
            return new Result(Code.ERROR.getValue(), "离职员工无法登录");
        }
        return new Result(Code.SUCCESS.getValue(), "登陆成功", admins1);
    }

    //    查询密码
    @PostMapping("/AdminPassword")
    public Result AdminPassword(@RequestBody admins admins) {
        admins admins1 = General.AdminLogin(admins);
        if (admins1 != null) {
            if (admins1.getAdminPassword().equals(admins.getAdminPassword())) {
                return new Result(Code.ERROR.getValue(), "新密码和旧密码相同");
            }
        }
        General.AdminPassword(admins);
        return new Result(Code.SUCCESS.getValue(), "修改成功");
    }

    //    查询所有库存分类
    @PostMapping("/ClassificationSelectAll")
    public Result ClassificationSelectAll() {
        List<Classification> classifications = General.ClassificationSelectAll();
        return new Result(Code.SUCCESS.getValue(), "查询成功", classifications);
    }
    // 添加入库记录

    @PostMapping("/Storage")

    public Result Storage(@RequestBody Storage storage) {
        // 判断仓库是否存在
        Stash stash = General.StashId(storage.getStorageStashId());
        if (stash == null) {
            return new Result(Code.ERROR.getValue(), "您选择入库的仓库不存在");
        }


        // 判断分类是否存在
        Integer classificationId = storage.getStorageClassificationId();
        Classification classification = General.classificationSelectId(classificationId);
        if (classification == null) {
            return new Result(Code.ERROR.getValue(), "您选择的商品分类不存在");
        }


        // 根据商品名、商品分类和商品规格判断商品是否不存在
        Product product = General.ProductSelectName(storage.getStorageName(), storage.getStorageClassificationId(), storage.getStorageVolume());
        if (product == null) {
            // 当商品不存在添加商品记录
            Product product1 = new Product();
            product1.setProductName(storage.getStorageName());
            product1.setProductNumber(storage.getStorageNumber());
            product1.setProductStash(String.valueOf(storage.getStorageStashId()));
            product1.setProductClassificationId(String.valueOf(storage.getStorageClassificationId()));
            product1.setProductTime(new Date());
            product1.setProductSpecification(storage.getStorageVolume());
            // 判断所在仓库容量是否满足存储商品内容
            DecimalFormat df1 = new DecimalFormat("#.000");
            Float volume = Float.valueOf(storage.getStorageNumber()) * Float.valueOf(df1.format(storage.getStorageVolume()));
            if (stash.getStashTotalCapacity() < stash.getStashCapacity() + volume) {
                return new Result(Code.ERROR.getValue(), "您所选择的现有容量无法装载货物，请选择其他仓库，或分批存入不同仓库");
            }
            stash.setStashCapacity(volume + stash.getStashCapacity());
            // 查询商品
            Boolean one = true;
            Random r = new Random();
            while (one) {
                String ids = "";
                for (int i = 0; i < 5; i++) {

                    ids += r.nextInt(8) + 1 + "";
                }
                Product product2 = new Product();
                product2.setProductId(Integer.valueOf(ids));
                Product product3 = General.ProductSelectId(product2);
                if (product3 == null) {
                    product1.setProductId(Integer.valueOf(ids));
                    one = false;
                }
            }
            storage.setStorageProductId(product1.getProductId());


            // 当商品不存在的时候添加数量表
            NumberFn numberFn = new NumberFn();
            numberFn.setNumber(storage.getStorageNumber());
            numberFn.setProductId(product1.getProductId());
            numberFn.setStashId(storage.getStorageStashId());
            General.NumberAdd(numberFn);
            General.StashUpdateCapacity(stash);
            General.ProductAdd(product1);
        } else {
            // 当商品存在修改商品记录
            storage.setStorageProductId(product.getProductId());
            product.setProductTime(new Date());
            product.setProductNumber(storage.getStorageNumber() + product.getProductNumber());
            // 查询数量表中是否存在该数量
            NumberFn numberFn1 = new NumberFn();
            numberFn1.setProductId(product.getProductId());
            numberFn1.setStashId(storage.getStorageStashId());


            if (product.getProductStash().indexOf(String.valueOf(storage.getStorageStashId())) == -1) {
                product.setProductStash(product.getProductStash() + "," + storage.getStorageStashId());
            }            // 判断所在仓库容量是否满足存储商品内容
            DecimalFormat df1 = new DecimalFormat("#.000");

            Float volume = Float.valueOf(storage.getStorageNumber()) * Float.valueOf(df1.format(storage.getStorageVolume()));
            if (stash.getStashTotalCapacity() < stash.getStashCapacity() + volume) {
                return new Result(Code.ERROR.getValue(), "您所选择的现有容量无法装载货物，请选择其他仓库，或分批存入不同仓库");
            }
            stash.setStashCapacity(volume + stash.getStashCapacity());

            NumberFn numberFn = General.NumberSelectAll(numberFn1);
            if (numberFn == null) {
//                return new Result(Code.ERROR.getValue(), "您所输入的仓库或者商品不存在");
                NumberFn numberFn2 = new NumberFn();
                numberFn2.setNumber(storage.getStorageNumber());
                numberFn2.setStashId(storage.getStorageStashId());
                numberFn2.setProductId(product.getProductId());
                General.NumberAdd(numberFn2);
            } else {
                numberFn.setNumber(numberFn.getNumber() + storage.getStorageNumber());
                General.NumberUpdateNumber(numberFn);
            }
            General.StashUpdateCapacity(stash);
            General.productUpdateInformation(product);
        }
        storage.setStorageTime(new Date());

        General.StorageAdd(storage);
        return new Result(Code.SUCCESS.getValue(), "添加成功");
    }

    // 添加出库记录
    @PostMapping("/StockRemoval")
    public Result StockRemoval(@RequestBody Storage storage) {
        // 查询出货商品是否存在
        Product product = new Product();
        product.setProductId(storage.getStorageProductId());
        Product product1 = General.ProductSelectId(product);
        if (product1 == null) {
            return new Result(Code.ERROR.getValue(), "您出库的商品可能不存在");
        }
        // 查询商品所在对应的仓库
        NumberFn numberFn = new NumberFn();
        numberFn.setProductId(storage.getStorageProductId());
        numberFn.setStashId(storage.getStorageStashId());
        NumberFn numberFn1 = General.NumberSelectAll(numberFn);
        if (numberFn1 == null) {
            return new Result(Code.ERROR.getValue(), "您出库的仓库可能不存在");
        }
        // 判断出库数量是否大于仓库原有数量
        if (numberFn1.getNumber() < storage.getStorageNumber()) {
            return new Result(Code.ERROR.getValue(), "您要出库" + storage.getStorageNumber() + "件商品，而您要出库的仓库只有" + numberFn1.getNumber() + "件商品，因此无法出库");
        }

        // 修改商品表
//        Product product2 = new Product();
        // 当出库商品等于现有商品，删除商品所在商品记录
        if (numberFn1.getNumber() == storage.getStorageNumber()) {
            String[] split = product1.getProductStash().split(",");
            String[] split1 = new String[split.length - 1];
            Integer index = 0;
            for (int i = 0; i < split.length; i++) {
                if (Integer.valueOf(split[i]) == (storage.getStorageStashId())) {
                    index = i;
                    break;
                }

            }
            for (int i = index; i < split.length; i++) {
                if (i != split.length - 1) {
                    split[i] = split[i + 1];
                }
            }
            for (int i = 0; i < split1.length; i++) {
                split1[i] = split[i];
            }
            String str = "";
            for (int i = 0; i < split1.length; i++) {
                if (i != split1.length - 1) {
                    str += (split1[i] + ",");
                } else {
                    str += (split1[i]);
                }
            }
            product1.setProductStash(str);
            // 当商品都数量不存在的时候删除该商品
            General.DeleteProduct(product1);

        }
//        product1.setProductTime(new Date());
//        product1.setProductNumber(product1.getProductNumber() - storage.getStorageNumber());
//        General.productUpdateInformation(product1);
        // 当一切条件正常修改数量记录表
        numberFn1.setNumber(numberFn1.getNumber() - storage.getStorageNumber());
        General.NumberUpdateNumber(numberFn1);
        // 修改仓库
        Stash stash = General.StashId(storage.getStorageStashId());
        stash.setStashCapacity(stash.getStashCapacity() - (storage.getStorageVolume() * storage.getStorageNumber()));
        General.StashUpdateCapacity(stash);
        // 添加新操作记录表
        storage.setStorageTime(new Date());
        storage.setStorageState(2);
        General.StorageAdd(storage);
        return new Result(Code.SUCCESS.getValue(), "出库成功");
    }


    //    查询所有库存分类
    @PostMapping("/ProductSelectLimit")
    public Result ProductSelectLimit(@RequestBody Page page) {
        if (page.getPageIndex() - 1 < 0) {
            return new Result(Code.ERROR.getValue(), "输入的参数有误");
        }
        page.setPageIndex((page.getPageIndex() - 1) * page.getPageSize());
        List<Product> classifications = General.ProductSelect();
        List<Product> classifications1 = General.ProductSelectLimit(page);
        classifications1.forEach(el -> {
            Classification classification = General.classificationSelectId(Integer.valueOf(el.getProductClassificationId()));
            el.setProductClassificationId(classification.getClassificationName());
            String[] split = el.getProductStash().split(",");
            List<Stash> stashes = General.StashSelectList(split);
            ObjectMapper om1 = new ObjectMapper();
            try {
                el.setProductStash(om1.writeValueAsString(stashes));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        });
        HashMap<Object, Object> map = new HashMap<>();
        map.put("Total", classifications.size());
        map.put("Date", classifications1);
        return new Result(Code.SUCCESS.getValue(), "查询成功", map);
    }

    @PostMapping("/ProductSelectId")
    public Result ProductSelectId(@RequestBody Product product) {
        Product product1 = General.ProductSelectId(product);
        if (product1 == null) {
            return new Result(Code.ERROR.getValue(), "查询失败");
        }
        return new Result(Code.SUCCESS.getValue(), "查询成功", product1);
    }

    @PostMapping("/StashSelectList")
    public Result StashSelectList(@RequestBody String[] strings) {
        List<Stash> stashes = General.StashSelectList(strings);
        if (stashes.size() < 0) {
            return new Result(Code.ERROR.getValue(), "查询失败");
        }
        return new Result(Code.SUCCESS.getValue(), "查询成功", stashes);
    }

    @PostMapping("/productUpdateClassification")
    public Result productUpdateClassification(@RequestBody Product product) {
        General.productUpdateClassification(product);
        return new Result(Code.SUCCESS.getValue(), "修改成功");
    }

    @PostMapping("/StorageSelectId")
    public Result StorageSelectId(@RequestBody Storage storage) {
        if (storage.getStorageState() == 3) {
            List<Storage> storages = General.StorageSelectAll(storage.getStorageProductId());
            return new Result(Code.SUCCESS.getValue(), "查询成功", storages);

        } else if (storage.getStorageState() == 1) {
            List<Storage> storages = General.StorageSelectId(storage.getStorageProductId(), 1);
            return new Result(Code.SUCCESS.getValue(), "查询成功", storages);

        } else if (storage.getStorageState() == 2) {
            List<Storage> storages = General.StorageSelectId(storage.getStorageProductId(), 2);
            return new Result(Code.SUCCESS.getValue(), "查询成功", storages);

        }
        return new Result(Code.SUCCESS.getValue(), "查询成功");

    }

    @PostMapping("/StorageSelect")
    public Result StorageSelect(@RequestBody Storage storage) {
        Storage storage1 = General.StorageSelect(storage.getStorageId());
        if (storage1 == null) {
            return new Result(Code.ERROR.getValue(), "查询失败");
        }
        admins admins = new admins();
        admins.setAdminId(Integer.valueOf(storage1.getStorageAdminId()));
        com.Stash.Domain.admins admins1 = Admin.AdminSelect(admins);
        storage1.setStorageAdminId(admins1.getAdminId() + "," + admins1.getAdminName());
        return new Result(Code.SUCCESS.getValue(), "查询成功", storage1);
    }


    @PostMapping("/StorageSelectIdEcharts")
    public Result StorageSelectIdEcharts(@RequestBody Storage storage) {


        List<Storage> storages = General.StorageSelectId(storage.getStorageProductId(), 1);
        Integer num = 0;
        if (storages.size() > 0) {
            for (int i = 0; i < storages.size(); i++) {
                num += storages.get(i).getStorageNumber();
            }
        }
        String str = "商品总数," + num;
        Product product = new Product();
        product.setProductId(storage.getStorageProductId());
        Product product1 = General.ProductSelectId(product);
        str += ",商品剩余数量," + product1.getProductNumber();
        int i = num - product1.getProductNumber();
        str += ",出库商品数," + i;

        return new Result(Code.SUCCESS.getValue(), "查询成功", str);
    }

    @PostMapping("/StashId")
    public Result StashId(@RequestBody Stash stash) {
        Stash stash1 = General.StashId(stash.getStashId());
        if (stash1 == null) {
            return new Result(Code.ERROR.getValue(), "输入的仓库id不存在");

        }

        return new Result(Code.SUCCESS.getValue(), "查询成功", stash1);
    }

    @PostMapping("/StashNumberFnProductAll")
    public Result StashNumberFnProductAll(@RequestBody Stash stash) {
        List<StashNumberFnProduct> stashNumberFnProducts = General.StashNumberFnProductAll(stash.getStashId());

        return new Result(Code.SUCCESS.getValue(), "查询成功", stashNumberFnProducts);
    }


    @PostMapping("/StashNumberFnProductClassAll")
    public Result StashNumberFnProductClassAll(@RequestBody Stash stash) {

        List<StashNumberFnProduct> stashNumberFnProducts = General.StashNumberFnProductClassAll(stash.getStashId());

        return new Result(Code.SUCCESS.getValue(), "查询成功", stashNumberFnProducts);
    }

    @PostMapping("/StorageSelectTime")
    public Result StorageSelectTime(@RequestBody Storage storage) throws ParseException {
        DateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String format = d.format(storage.getStorageTime());
        String[] split = format.split("-");
        split[1] = Integer.valueOf(format.split("-")[1]) + 1 + "";
        String str = "";
        for (int i = 0; i < split.length; i++) {
            if(i!= split.length-1){
                str+=split[i]+"-";
            }else{
                str+=split[i];
            }
        }

        Date parse = d.parse(str);
        List<Storage> storages = General.StorageSelectTime(storage.getStorageTime(), parse, storage.getStorageStashId());

        return new Result(Code.SUCCESS.getValue(), "查询成功", storages);
    }


}
